package com.lingxu.base.config;

import com.lingxu.base.common.shiro.authc.ShiroRealm;
import com.lingxu.base.common.shiro.authc.aop.JwtFilter;
import com.lingxu.base.common.util.ObjectConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author: Scott
 * @date: 2018/2/7
 * @description: shiro 配置类
 */

@Slf4j
@Configuration
public class ShiroConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private String port;

    @Value("${spring.redis.database}")
    private Integer dbIndex;

    @Value("${spring.redis.password}")
    private String redisPassword;

    /**
     * Filter Chain定义说明
     * <p>
     * 1、一个URL可以配置多个Filter，使用逗号分隔
     * 2、当设置多个过滤器时，全部验证通过，才视为通过
     * 3、部分过滤器可指定参数，如perms，roles
     */
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 拦截器
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();

        //cas验证登录
		filterChainDefinitionMap.put("/userrole/sysUserRole/**", "anon");
		filterChainDefinitionMap.put("/finance/**", "anon");
		// 配置不会被拦截的链接 顺序判断
		filterChainDefinitionMap.put("/webApi/webApi", "anon");
        filterChainDefinitionMap.put("/first/getNameList", "anon");

        filterChainDefinitionMap.put("/sys/loginByNamePwd", "anon"); //登录接口排除
        filterChainDefinitionMap.put("/sys/loginFxxt", "anon"); //登录接口排除
        filterChainDefinitionMap.put("/sys/logout", "anon"); //登出接口排除
        filterChainDefinitionMap.put("/sys/user/register", "anon");//用户注册
        filterChainDefinitionMap.put("/system/manage/sysUser/updatePassword", "anon");//修改密码


        filterChainDefinitionMap.put("/sys/file/upload", "anon");//文件上传
        filterChainDefinitionMap.put("/sys/file/uploadFile", "anon");//文件上传

		filterChainDefinitionMap.put("/service/**", "anon");
		filterChainDefinitionMap.put("/service/editor/stencilset", "anon");
		filterChainDefinitionMap.put("/service/model/*/json", "anon");
		filterChainDefinitionMap.put("/service/model/*/save", "anon");

//        filterChainDefinitionMap.put("/found/**", "anon");
//        filterChainDefinitionMap.put("/payMent/**", "anon");

        /*=====================调试开放接口拦截======================================*/
        filterChainDefinitionMap.put("/sys/JwXjLogin", "anon"); //单点登录接口排除

        filterChainDefinitionMap.put("/systemDict/updateSystemDictCityCache", "anon");
        filterChainDefinitionMap.put("/systemDict/updateSystemDictCache", "anon");
        filterChainDefinitionMap.put("/systemDict/updateSystemDictTreeCache", "anon");
        filterChainDefinitionMap.put("/person/personInfo/importPerson", "anon");
        filterChainDefinitionMap.put("/person/personInfo/disposePerson", "anon");
        filterChainDefinitionMap.put("/company/importWorkData", "anon");
        filterChainDefinitionMap.put("/company/findNJAreaTreeList", "anon");
        filterChainDefinitionMap.put("/financeSupervise/findMaxDate", "anon");

        filterChainDefinitionMap.put("/travelRoute/AnalysisRecord", "anon");
        filterChainDefinitionMap.put("/earlyWarn/exportExcelFile", "anon");

        filterChainDefinitionMap.put("/hdfx/exportExcelFile", "anon");
        filterChainDefinitionMap.put("/track/travelRoute/exportExcelFile", "anon");
        filterChainDefinitionMap.put("/found/exportExcelFile", "anon");
        filterChainDefinitionMap.put("/export/**", "anon");
        filterChainDefinitionMap.put("/redList/exportRedList", "anon");
        filterChainDefinitionMap.put("/redList/exportMode", "anon");
        filterChainDefinitionMap.put("/redList/compareToRedList", "anon");
        filterChainDefinitionMap.put("/use/data/findNeedApprovalList", "anon");
        filterChainDefinitionMap.put("/system/sysLog/downLogFilePDF", "anon");
        filterChainDefinitionMap.put("/report/exportReport", "anon");
        filterChainDefinitionMap.put("/report/exportReportByRun", "anon");
        filterChainDefinitionMap.put("/system/sysLog/createBackUpFile", "anon");
        filterChainDefinitionMap.put("/system/manage/sysDepart/findDepartTreeByLogin", "anon");
        filterChainDefinitionMap.put("/system/manage/sysUser/list", "anon");

        filterChainDefinitionMap.put("/homeIndex/findModelDataExcel", "anon");
//        filterChainDefinitionMap.put("/result/feedBack/findModelFeedBackList", "anon");
        filterChainDefinitionMap.put("/model/score/**", "anon");



        /**
         * 测试
         */
        filterChainDefinitionMap.put("/neo4j/test", "anon");
        filterChainDefinitionMap.put("/neo4j/setNeo4jData", "anon");

        filterChainDefinitionMap.put("/", "anon");
        filterChainDefinitionMap.put("/doc.html", "anon");
        filterChainDefinitionMap.put("/**/*.js", "anon");
        filterChainDefinitionMap.put("/**/*.css", "anon");
        filterChainDefinitionMap.put("/**/*.json", "anon");
        filterChainDefinitionMap.put("/**/*.xml", "anon");
        filterChainDefinitionMap.put("/**/*.html", "anon");
        filterChainDefinitionMap.put("/**/*.svg", "anon");
        filterChainDefinitionMap.put("/**/*.pdf", "anon");
        filterChainDefinitionMap.put("/**/*.mp4", "anon");
        filterChainDefinitionMap.put("/**/*.txt", "anon");
        filterChainDefinitionMap.put("/**/*.doc", "anon");
        filterChainDefinitionMap.put("/**/*.docx", "anon");
        filterChainDefinitionMap.put("/**/*.xls", "anon");
        filterChainDefinitionMap.put("/**/*.xlsx", "anon");
        filterChainDefinitionMap.put("/**/*.jpg", "anon");
        filterChainDefinitionMap.put("/**/*.png", "anon");
        filterChainDefinitionMap.put("/**/*.ico", "anon");

        filterChainDefinitionMap.put("/res/*", "anon");

        // update-begin--Author:sunjianlei Date:20190813 for：排除字体格式的后缀
        filterChainDefinitionMap.put("/**/*.ttf", "anon");
        filterChainDefinitionMap.put("/**/*.woff", "anon");
        filterChainDefinitionMap.put("/**/*.woff2", "anon");
        // update-begin--Author:sunjianlei Date:20190813 for：排除字体格式的后缀

        filterChainDefinitionMap.put("/druid/**", "anon");
        filterChainDefinitionMap.put("/swagger-ui.html", "anon");
        filterChainDefinitionMap.put("/swagger**/**", "anon");
        filterChainDefinitionMap.put("/webjars/**", "anon");
        filterChainDefinitionMap.put("/v2/**", "anon");
        //本地测试接口
        filterChainDefinitionMap.put("/constructionDrawingDesign/**", "anon");
        filterChainDefinitionMap.put("/designChangeManagement/**", "anon");
        filterChainDefinitionMap.put("/subcontractManagement/**", "anon");
        filterChainDefinitionMap.put("/formalHandoverAcceptance/**", "anon");
        filterChainDefinitionMap.put("/multiCompletionAcceptance/**", "anon");
        filterChainDefinitionMap.put("/feasibilityReviewMeeting/**", "anon");
        filterChainDefinitionMap.put("/traffic/**", "anon");
        filterChainDefinitionMap.put("/projectbase/**", "anon");
        filterChainDefinitionMap.put("/projectSchedule/**", "anon");
        filterChainDefinitionMap.put("/projectConstructionInfo/**", "anon");
        filterChainDefinitionMap.put("/getTBUnitController/**", "anon");
        filterChainDefinitionMap.put("/projectPreDesign/**", "anon");
        filterChainDefinitionMap.put("/projectApproval/**", "anon");
        filterChainDefinitionMap.put("/constructionPermit/**", "anon");
        filterChainDefinitionMap.put("/y029Xmk/**", "anon");
        filterChainDefinitionMap.put("/cProjectExtendInfo/**", "anon");
        filterChainDefinitionMap.put("/projectInfo/**", "anon");
        filterChainDefinitionMap.put("/risk/**", "anon");
        filterChainDefinitionMap.put("/overview/**", "anon");
        filterChainDefinitionMap.put("/modelcategory/**", "anon");
        filterChainDefinitionMap.put("/defectLiabilityPeriod/**", "anon");
        filterChainDefinitionMap.put("/sjcsJgysb1/**", "anon");
        filterChainDefinitionMap.put("/qualityManagement/**", "anon");
        filterChainDefinitionMap.put("/sjtjfx/**", "anon");
        filterChainDefinitionMap.put("/change/**", "anon");


        // 添加自己的过滤器并且取名为jwt
        Map<String, Filter> filterMap = new HashMap<String, Filter>(1);
        filterMap.put("jwt", new JwtFilter());
        shiroFilterFactoryBean.setFilters(filterMap);
        // <!-- 过滤链定义，从上向下顺序执行，一般将/**放在最为下边
        filterChainDefinitionMap.put("/**", "jwt");

        // 未授权界面返回JSON
        shiroFilterFactoryBean.setUnauthorizedUrl("/sys/common/403");
        shiroFilterFactoryBean.setLoginUrl("/sys/common/403");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    @Bean("securityManager")
    public DefaultWebSecurityManager securityManager(ShiroRealm myRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm);

        /*
         * 关闭shiro自带的session，详情见文档
         * http://shiro.apache.org/session-management.html#SessionManagement-
         * StatelessApplications%28Sessionless%29
         */
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
        securityManager.setSubjectDAO(subjectDAO);
        //自定义缓存实现,使用redis
        securityManager.setCacheManager(redisCacheManager());
        return securityManager;
    }

    /**
     * 下面的代码是添加注解支持
     *
     * @return
     */
    @Bean
    @DependsOn("lifecycleBeanPostProcessor")
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
        return defaultAdvisorAutoProxyCreator;
    }

    @Bean
    public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }

    /**
     * cacheManager 缓存 redis实现
     * 使用的是shiro-redis开源插件
     *
     * @return
     */
    public RedisCacheManager redisCacheManager() {
        log.info("===============(1)创建缓存管理器RedisCacheManager");
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        //redis中针对不同用户缓存(此处的id需要对应user实体中的id字段,用于唯一标识)
        redisCacheManager.setPrincipalIdFieldName("id");
        //用户权限信息缓存时间
        redisCacheManager.setExpire(200000);
        return redisCacheManager;
    }

    /**
     * 配置shiro redisManager
     * 使用的是shiro-redis开源插件
     *
     * @return
     */
    @Bean
    public RedisManager redisManager() {
        log.info("===============(2)创建RedisManager,连接Redis..URL= " + host + ":" + port);
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(host);
        redisManager.setPort(ObjectConvertUtils.getInt(port));
        redisManager.setTimeout(0);
        redisManager.setDatabase(dbIndex);
        if (redisPassword != null && !"".equals(redisPassword.trim())) {
            redisManager.setPassword(redisPassword);
        }
        return redisManager;
    }

}
